package cn.jinjimi.app.modules.Theme;

import cn.jinjimi.base.preference.PreferenceManager;
import cn.jinjimi.base.util.FileUtils;
import cn.jinjimi.base.util.GsonUtils;
import cn.jinjimi.base.util.StringUtils;
import cn.jinjimi.app.AppContext;
import cn.jinjimi.app.modules.Theme.entity.CompanyColor;
import cn.jinjimi.app.modules.Theme.entity.CompanyColorDTO;
import cn.jinjimi.app.bean.SharePrefKeys;

import java.util.HashMap;
import java.util.Map;

/**
 * Created by Roy
 * Date: 2017/3/27
 */

public class ZdbThemeManager {

    private static volatile ZdbThemeManager instance = null;
    private static final String ZdbThemeMapJsonName = "xrk_theme_setting.json";

    // 当前主题的MD5
    private String md5;
    // 下载的文件存储地址
    private String filePath = FileUtils.getAppCache(AppContext.getInstance(), "theme");
    private String fileName = filePath + ZdbThemeMapJsonName;

    private Map<String, String> companyColorMap = new HashMap<>();

    /* 双重检验锁的懒汉模式的单例模式*/
    public static ZdbThemeManager getInstance() {
        if (instance == null) {
            synchronized (ZdbThemeManager.class) {
                if (instance == null)
                    instance = new ZdbThemeManager();
            }
        }
        return instance;
    }

    public ZdbThemeManager() {
        init();
    }

    private void init() {
        md5 = PreferenceManager.getStringData(SharePrefKeys.PREF_ZDB_THEME_MD5);

        analyTheme();
    }

    /* 检查是否需要下载新的json文件 */
    public void checkConfig() {
        ZdbTheme.Config config = ZdbTheme.getInstance().getConfig();

        if (config != null) {
            if (StringUtils.isEmpty(config.md5) || (config.md5.equals(md5) && !FileUtils.checkFileisEmpty(filePath)))
                return;

            FileUtils.deleteAllFile(filePath);

            //TODO
            //start download
        }
    }

    /* 解析JSON文件 */
    private void analyTheme() {
        CompanyColorDTO companyColorDTO = GsonUtils.fromJson(FileUtils.getFileString(fileName), CompanyColorDTO.class);
        if (companyColorDTO != null && companyColorDTO.companies != null) {
            companyColorMap.clear();
            for (CompanyColor companyColor : companyColorDTO.companies) {
                companyColorMap.put(companyColor.code, companyColor.color);
            }
        }
    }

    /**
     * 根据公司Code获取公司对应的颜色值
     *
     * @param code
     * @return
     */
    public String getCompanyColor(String code) {
        if (companyColorMap.containsKey(code))
            return companyColorMap.get(code);
        else
            return "#FF6430";
    }
}
